﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Deployment.Application;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
using System.Threading.Tasks;

using ScarecrowLibrary;
using ScarecrowLibrary.Network;
using ScarecrowLibrary.IO;

namespace Scarecrow_Network_Manager
{
    /// <summary>
    /// Logica di interazione per MainWindow.xaml
    /// </summary>
    public partial class oldMainWindow : Window
    {
        #region Properties
        string UnknowProfile { get { return Properties.Resources.UnknowProfile; } }
        #endregion

        #region Fields
        bool forceClose = false;
        scNetworkProfile selected, toActivate, active;
        BackgroundWorker worker;
        #endregion

        #region Form Methods
        public oldMainWindow()
        {
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Properties.Settings.Default.Language);

            InitializeComponent();

            this.worker = new BackgroundWorker();
            this.worker.WorkerReportsProgress = true;
            this.worker.WorkerSupportsCancellation = true;
            this.worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            this.worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            this.worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

            #region First Run
            if (System.IO.File.Exists("\firstrun.txt"))
            {
                System.IO.File.Delete("\firsrun.txt");

                if(System.IO.Directory.Exists(Properties.Settings.Default.ProfilesPath))
                {
                    System.IO.Directory.Move(Properties.Settings.Default.ProfilesPath, Global.ProfilesPath);
                }
            }
            #endregion

            #region Autostart Enforcement
            if (Properties.Settings.Default.AutoStart)
            {
                try
                {
                    ScarecrowLibrary.scApplicationAutostarter.UnSetAutoStart(Global.ProductName);
                }
                catch { }
                try
                {
                    ScarecrowLibrary.scApplicationAutostarter.SetAutoStart(Global.ProductName, Global.PublisherName, new string[] { "-s" });
                }
                catch { }
            }
            #endregion

            #region Creating User Folder
            try
            {
                if (!System.IO.Directory.Exists(Global.ProfilesPath))
                    System.IO.Directory.CreateDirectory(Global.ProfilesPath);
                if (!System.IO.Directory.Exists(Properties.Settings.Default.ImagesPath))
                    System.IO.Directory.CreateDirectory(Properties.Settings.Default.ImagesPath);
                if (!System.IO.Directory.Exists(Properties.Settings.Default.ImagesPath))
                    System.IO.Directory.CreateDirectory(Properties.Settings.Default.ImagesPath);

                string[] files = System.IO.Directory.GetFiles(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Images\\Profiles\\");
                foreach (string file in files)
                {
                    string outFile = Properties.Settings.Default.ImagesPath + System.IO.Path.GetFileName(file);
                    if (!System.IO.File.Exists(outFile))
                        System.IO.File.Copy(file, outFile, false);
                }
            }
            catch (Exception e)
            {
                Global.NotifyCrash(Properties.Resources.Error_UserFolder, e);
            }
            #endregion

            #region Updater
            try
            {
                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    ApplicationDeployment.CurrentDeployment.CheckForUpdateProgressChanged += new DeploymentProgressChangedEventHandler(CurrentDeployment_CheckForUpdateProgressChanged);
                    ApplicationDeployment.CurrentDeployment.CheckForUpdateCompleted += new CheckForUpdateCompletedEventHandler(CurrentDeployment_CheckForUpdateCompleted);
                    ApplicationDeployment.CurrentDeployment.UpdateProgressChanged += new DeploymentProgressChangedEventHandler(CurrentDeployment_UpdateProgressChanged);
                    ApplicationDeployment.CurrentDeployment.UpdateCompleted += new AsyncCompletedEventHandler(CurrentDeployment_UpdateCompleted);

                    ApplicationDeployment.CurrentDeployment.CheckForUpdateAsync();
                }
                else
                {
                    this.lblInfo.Content = string.Format("{0}: {1}", Properties.Resources.DebugVersion, ScarecrowLibrary.scEnvironment.ApplicationVersion);
                }
            }
            catch (Exception e)
            {
                Global.NotifyCrash(Properties.Resources.Error_UpdateSearch, e);
            }
            #endregion
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            LoadProfiles();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            try
            {
                if (Properties.Settings.Default.NotifyHide && !forceClose)
                {
                    e.Cancel = true;
                    this.WindowState = System.Windows.WindowState.Minimized;
                }
                this.mainGrid.Focus();
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_WindowsClosing, exc);
            }
        }
        private void Window_Activated(object sender, EventArgs e)
        {
            UpdateBookmarks();
        }
        #endregion

        #region Updater
        private void cmdUpdate_Click(object sender, RoutedEventArgs e)
        {
            ApplicationDeployment.CurrentDeployment.UpdateAsync();
            this.cmdUpdate.IsEnabled = false;
        }
        void CurrentDeployment_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
        {
            this.lblInfo.Content = string.Format("{0}: {1}% - {2} / {3} - {4}", Properties.Resources.UpdateInProgress, e.ProgressPercentage, scStringTools.FormatUnit((ulong)e.BytesCompleted, "B"), scStringTools.FormatUnit((ulong)e.BytesTotal, "B"), e.State);
        }
        void CurrentDeployment_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error == null && !e.Cancelled)
            {
                this.lblInfo.Content = Properties.Resources.RebootNeeded;
            }
            else if (e.Error != null)
            {
                this.lblInfo.Content = e.Error.ToString();
                this.cmdUpdate.IsEnabled = true;
            }
            else
            {
                this.lblInfo.Content = Properties.Resources.UpdateCancelled;
                this.cmdUpdate.IsEnabled = true;
            }
        }

        void CurrentDeployment_CheckForUpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
        {
            this.lblInfo.Content = string.Format("{0}: {1}% - {2} / {3} - {4}", Properties.Resources.UpdateSearch, e.ProgressPercentage, scStringTools.FormatUnit((ulong)e.BytesCompleted, "B"), scStringTools.FormatUnit((ulong)e.BytesTotal, "B"), e.State);
        }

        void CurrentDeployment_CheckForUpdateCompleted(object sender, CheckForUpdateCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null && !e.Cancelled && e.UpdateAvailable)
                {
                    this.cmdUpdate.Visibility = System.Windows.Visibility.Visible;
                    if (!e.IsUpdateRequired && e.AvailableVersion > ApplicationDeployment.CurrentDeployment.CurrentVersion)
                        this.lblInfo.Content = string.Format("{0}: {1}", Properties.Resources.UpdateAvailable, e.AvailableVersion);
                    else
                    {
                        ApplicationDeployment.CurrentDeployment.Update();
                        System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
                        Application.Current.Shutdown();
                    }
                }
                else
                {
                    this.cmdUpdate.Visibility = System.Windows.Visibility.Hidden;
                    this.lblInfo.Content = string.Format("{0}: {1}", Properties.Resources.CurrentVersion,ScarecrowLibrary.scEnvironment.ApplicationVersion);
                }
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_Updating, exc);
            }
        }
        #endregion

        #region Command
        private void cmdSettings_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SettingsWindow window = new SettingsWindow();
                window.ShowDialog();
                this.mainGrid.Focus();
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_SettingsClicked, exc);
            }
        }
        private void lstProfiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (this.lstProfiles.SelectedItem != null)
                {
                    scNetworkProfile np = new scNetworkProfile();
                    string profile = ((StackPanel)lstProfiles.SelectedItem).Tag.ToString();
                    scXmlSerializer.Load(ref np, "np", System.IO.Path.Combine(Global.ProfilesPath, profile));
                    string info = string.Format("{2}:\t\t{1}{0}{0}", Environment.NewLine, np.Name, Properties.Resources.Profile);
                    scAdapterProfile[] aps = np.GetProfiles();
                    aps = aps.OrderBy((ap) => !ap.Enabled).ToArray();
                    for (int i = 0; i < aps.Length; i++)
                    {
                        scAdapterProfile ap = aps[i];
                        info += "\t-------------------------------------------------------------" + Environment.NewLine;
                        info += string.Format("{10}:\t\t{1}{0}{0}{0}{11}:\t\t{2}{0}{0}{12}:\t{8}{0}{13}:\t{3}{0}{14}:\t{4}{0}{15}:\t\t{5}{0}{0}{16}:\t{9}{0}{17}:\t{6}{0}{18}:\t{7}{0}",
                            Environment.NewLine, ap.NetworkAdapter, (ap.Enabled ? Properties.Resources.Yes : Properties.Resources.No), (ap.Enabled ? ap.IPAddress : ""), (ap.Enabled ? ap.SubnetMask : ""), (ap.Enabled ? ap.Gateway : ""), (ap.Enabled ? ap.DNS1 : ""), (ap.Enabled ? ap.DNS2 : ""), (ap.IsIPDhcp ? Properties.Resources.Yes : Properties.Resources.No), (ap.IsDNSDhcp ? Properties.Resources.Yes : Properties.Resources.No),
                            Properties.Resources.Adapter, Properties.Resources.Enable, Properties.Resources.DHCPIP, Properties.Resources.IPAddress, Properties.Resources.SubnetMask, Properties.Resources.Gateway, Properties.Resources.DHCPDNS, Properties.Resources.DNS1, Properties.Resources.DNS2);
                    }
                    this.lblProfile.Text = info;
                    this.cmdActivate.Visibility = Visibility.Visible;
                    this.selected = np;
                }
                else
                {
                    this.lblProfile.Text = "";
                    this.cmdActivate.Visibility = Visibility.Hidden;
                    this.selected = null;
                }
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_ProfileActivating, exc);
            }
        }
        private void cmdAddProfile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                oldProfileWindow window = new oldProfileWindow(null);
                window.ShowDialog();
                if (window.Profile != null)
                {
                    bool active = false;
                    if (window.ToRemove != null)
                    {
                        System.IO.File.Delete(System.IO.Path.Combine(Global.ProfilesPath, window.ToRemove));
                        StackPanel sp = null;
                        foreach (var item in this.lstProfiles.Items)
                        {
                            sp = (item as StackPanel);
                            if(sp.Tag.ToString() == window.ToRemove)
                            {
                                active = (sp.Children[1] as TextBlock).Text.Contains(string.Format("({0})", Properties.Resources.ProfileActive));
                                this.lstProfiles.Items.Remove(sp);
                                break;
                            }
                        }
                    }
                    scNetworkProfile np = new scNetworkProfile();
                    scXmlSerializer.Load(ref np, "np", System.IO.Path.Combine(Global.ProfilesPath, window.Profile));
                    ProfileToList(np, active);
                }
                this.mainGrid.Focus();
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_BookmarkCreation, exc);
            }
        }

        private void cmdEdit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StackPanel selected = this.lstProfiles.SelectedItem as StackPanel;
                if (selected != null)
                {
                    string selectedName = selected.Tag.ToString();
                    oldProfileWindow window = new oldProfileWindow(selectedName);
                    bool? removeOld = window.ShowDialog();
                    if (window.Profile != null)
                    {
                        //se il nuovo nome non coincide con il nome vecchio
                        //guardo se c'è un altro elemento che condivide il nuovo nome e nel caso lo tolgo

                        string newName = window.Profile;

                        if (selectedName != newName)
                        {
                            for (int i = 0; i < this.lstProfiles.Items.Count; i++)
                            {
                                StackPanel obj = this.lstProfiles.Items[i] as StackPanel;
                                if (obj.Tag.ToString() == newName)
                                {
                                    this.lstProfiles.Items.Remove(this.lstProfiles.Items[i]);
                                    break;
                                }
                            }
                        }
                        
                        //tolgo il vecchio profilo e aggiungo quello nuovo
                        this.lstProfiles.Items.Remove(selected);
                        scNetworkProfile np = new scNetworkProfile();
                        scXmlSerializer.Load(ref np, "np", System.IO.Path.Combine(Global.ProfilesPath, window.Profile));
                        bool isActive = (selected.Children[1] as TextBlock).Text.Contains(string.Format("({0})", Properties.Resources.ProfileActive));
                        ProfileToList(np, isActive);
                    }
                    this.mainGrid.Focus();
                }
                this.mainGrid.Focus();
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_ProfileEditing, exc);
            }
        }

        private void cmdDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.lstProfiles.SelectedItem != null)
                {
                    if (MessageBox.Show(Properties.Resources.ProfileDeleting, Properties.Resources.Warning, MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                    {
                        string profile = ((StackPanel)lstProfiles.SelectedItem).Tag.ToString();
                        System.IO.File.Delete(System.IO.Path.Combine(Global.ProfilesPath, profile));
                        
                        if (Properties.Settings.Default.Preferito1 == profile)
                            Properties.Settings.Default.Preferito1 = null;
                        if (Properties.Settings.Default.Preferito2 == profile)
                            Properties.Settings.Default.Preferito2 = null;
                        if (Properties.Settings.Default.Preferito3 == profile)
                            Properties.Settings.Default.Preferito3 = null;
                        if (Properties.Settings.Default.Preferito4 == profile)
                            Properties.Settings.Default.Preferito4 = null;
                        Properties.Settings.Default.Save();

                        if (((this.lstProfiles.SelectedItem as StackPanel).Children[1] as TextBlock).Text.Contains(string.Format("({0})", Properties.Resources.ProfileActive)))
                            LoadProfiles();
                        else
                            this.lstProfiles.Items.Remove(this.lstProfiles.SelectedItem);
                        UpdateBookmarks();
                    }
                }
                this.mainGrid.Focus();
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_ProfileDeleting, exc);
            }
        }

        private void cmdActivate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.selected != null && this.worker != null && !this.worker.IsBusy)
                {
                    LockGUI(true);
                    this.lblProgress.Visibility = this.prgProgress.Visibility = Visibility.Visible;
                    this.TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Normal;
                    this.toActivate = this.selected;
                    this.worker.RunWorkerAsync();
                }
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_ProfileActivating, exc);
            }
        }

        private void ThumbButtonInfo_Click(object sender, EventArgs e)
        {
            forceClose = true;
            Close();
        }

        void LoadBookmark(string path)
        {
            try
            {
                if (!String.IsNullOrWhiteSpace(path))
                {
                    path = System.IO.Path.Combine(Global.ProfilesPath, path);
                    if (System.IO.File.Exists(path))
                    {
                        scNetworkProfile np = new scNetworkProfile();
                        scXmlSerializer.Load(ref np, "np", path);

                        ThumbButtonInfo p = new ThumbButtonInfo();
                        p.Description = np.Name;
                        p.ImageSource = Global.LoadImageFromPath(np.ImagePath).Source;
                        p.Click += ChooseBookmark;

                        this.TaskbarItemInfo.ThumbButtonInfos.Add(p);
                    }
                }
            }
            catch (Exception e)
            {
                Global.NotifyCrash(Properties.Resources.Error_BookmarkActivating, e);
            }
        }

        private void txtFilter_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.lstProfiles.Items.Filter = i => ((string)((StackPanel)i).Tag).ToLower().Contains(this.txtFilter.Text.ToLower());
        }
        #endregion

        #region My Methods
        private void lstProfiles_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.cmdEdit.IsEnabled)
                cmdActivate_Click(sender, null);
        }

        void LockGUI(bool gLock)
        {
                //this.lstProfiles.IsEnabled = 
            this.cmdFix.IsEnabled =
            this.cmdDelete.IsEnabled =
            this.cmdEdit.IsEnabled =
            this.cmdAddProfile.IsEnabled =
            this.txtFilter.IsEnabled = !gLock;
        }
        void UpdateBookmarks()
        {
            try{
            this.TaskbarItemInfo.ThumbButtonInfos.Clear();
            LoadBookmark(Properties.Settings.Default.Preferito1);
            LoadBookmark(Properties.Settings.Default.Preferito2);
            LoadBookmark(Properties.Settings.Default.Preferito3);
            LoadBookmark(Properties.Settings.Default.Preferito4);

            ThumbButtonInfo cmdClose = new ThumbButtonInfo();
            cmdClose.Description = "Chiudi";
            cmdClose.ImageSource = Global.LoadImageFromResource("Images\\System\\delete.png").Source;
            cmdClose.Click += ThumbButtonInfo_Click;
            this.TaskbarItemInfo.ThumbButtonInfos.Add(cmdClose);
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_BookmarkCreation, exc);
            }
        }

        void lpa_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker lpa = (sender as BackgroundWorker);
            try
            {
                string unknowPath = System.IO.Path.Combine(Global.ProfilesPath, UnknowProfile);
                //se esiste elimino il profilo sconosciuto
                if (System.IO.File.Exists(unknowPath))
                    System.IO.File.Delete(unknowPath);

                //Creo il profilo che indica la configurazione corrente
                scNetworkProfile current = scNetworkProfile.GetCurrentProfile();

                //Carico tutti i profili
                bool match = false, matchFlag = false;
                string[] files = System.IO.Directory.GetFiles(Global.ProfilesPath);
                foreach (string file in files)
                {
                    scNetworkProfile np = new scNetworkProfile();
                    scXmlSerializer.Load(ref np, "np", file);
                    current.Name = np.Name;
                    current.ImagePath = np.ImagePath;
                    matchFlag |= match = np == current;
                    lpa.ReportProgress(Convert.ToInt32(match), np);
                }
                if (!matchFlag)
                {
                    current.Name = UnknowProfile;
                    current.ImagePath = System.IO.Path.Combine(Properties.Settings.Default.ImagesPath, "dhcp.png");
                    scXmlSerializer.Save(current, "np", unknowPath);
                    lpa.ReportProgress(Convert.ToInt32(true), current);
                }
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_ProfileLoading, exc);
            }
        }
        void LoadProfiles()
        {
            BackgroundWorker lpa = new BackgroundWorker();
            lpa.WorkerReportsProgress = true;
            lpa.WorkerSupportsCancellation = true;
            lpa.DoWork +=new DoWorkEventHandler(lpa_DoWork);
            lpa.ProgressChanged += new ProgressChangedEventHandler(lpa_ProgressChanged);
            lpa.RunWorkerCompleted += new RunWorkerCompletedEventHandler(lpa_RunWorkerCompleted);

            this.lblProfile.Text = Properties.Resources.ProfileLoading;
            // Elimino la lista dei profili
            LockGUI(true);
            this.lstProfiles.Items.Clear();
            lpa.RunWorkerAsync();
        }

        void lpa_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            LockGUI(false);
            UpdateBookmarks();
            this.lblProfile.Text = "";
        }

        void lpa_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            scNetworkProfile profile = e.UserState as scNetworkProfile;
            ProfileToList(profile, Convert.ToBoolean(e.ProgressPercentage));
            this.lstProfiles.Items.Refresh();
        }

        void ProfileToList(scNetworkProfile np, bool isActive)
        {
            StackPanel sp = new StackPanel();
            sp.Name = "sp" + this.lstProfiles.Items.Count.ToString();
            sp.Tag = np.Name;
            sp.Width = this.lstProfiles.Width - 16;

            Image icon = Global.LoadImageFromPath(np.ImagePath);
            icon.Stretch = Stretch.None;
            icon.Source = Global.ResizeImage(icon.Source, 64, 64);
            sp.Children.Add(icon);

            TextBlock tb = new TextBlock();
            tb.TextAlignment = TextAlignment.Center;
            tb.Text = np.Name;
            tb.Margin = new Thickness(0, 0, 0, 15);

            sp.Children.Add(tb);
            sp.Width = sp.Width - 10;

            if (isActive)
            {
                tb.Background = Brushes.GreenYellow;
                tb.Text += Environment.NewLine + string.Format("({0})", Properties.Resources.ProfileActive);
                this.lstProfiles.Items.Insert(0, sp);
                this.active = np;
            }
            else
            {
                this.lstProfiles.Items.Add(sp);
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.cmdActivate.IsEnabled = this.cmdAddProfile.IsEnabled = this.cmdDelete.IsEnabled = this.cmdEdit.IsEnabled = true;
            this.TaskbarItemInfo.ProgressValue = 0;
            this.prgProgress.Value = 0;
            this.lblProgress.Visibility = this.prgProgress.Visibility = Visibility.Hidden;
            this.TaskbarItemInfo.ProgressState = TaskbarItemProgressState.None;
            this.mainGrid.Focus();
            for (int i = 0; i < this.lstProfiles.Items.Count; i++)
            {
                StackPanel sp = this.lstProfiles.Items[i] as StackPanel;
                TextBlock tb = sp.Children[1] as TextBlock;
                if (sp != null && sp.Tag.ToString() == this.toActivate.Name)
                {
                    this.lstProfiles.Items.Remove(this.lstProfiles.Items[i]);
                }
                else if (tb != null && tb.Text.ToLower().Contains(string.Format("({0})", Properties.Resources.ProfileActive)))
                {
                    tb.Background = Brushes.Transparent;
                    tb.Text = tb.Text.Remove(tb.Text.IndexOf(string.Format("({0})", Properties.Resources.ProfileActive)) - 2);
                }
            }
            ProfileToList(this.toActivate, true);
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.prgProgress.Value = e.ProgressPercentage;
            this.lblProgress.Content = e.UserState;
            this.TaskbarItemInfo.ProgressValue = (double)e.ProgressPercentage / 100.0;
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                scAdapterProfile[] profiles = this.selected.GetProfiles();
                int progress = 0;
                profiles = profiles.OrderBy((p) => p.Enabled).ToArray();
                int step = 100 / (profiles.Length * 3);

                for (int i = 0; i < profiles.Length; i++)
                {
                    try
                    {
                        if (e.Cancel)
                            return;

                        scAdapterProfile profile = profiles[i];
                        scNetworkAdapter adapter = new scNetworkAdapter(profile.NetworkAdapter);

                        if (profile.Enabled)
                        {
                            adapter.Enable();
                            progress += step;
                            this.worker.ReportProgress(progress, string.Format("{0} \"{1}\" {2}", Properties.Resources.Adapter, profile.NetworkAdapter, Properties.Resources.Enabled));

                            if (profile.IsIPDhcp)
                            {
                                adapter.SetIPDHCP();
                            }
                            else
                            {
                                adapter.SetIPAddress(profile.IPAddress, profile.SubnetMask, profile.Gateway);
                            }
                            progress += step;
                            this.worker.ReportProgress(progress, string.Format("{0}, {1}, {2}: {3}", Properties.Resources.IPAddress, Properties.Resources.SubnetMask, Properties.Resources.Gateway, Properties.Resources.Configured));

                            if (profile.IsDNSDhcp)
                            {
                                adapter.SetDNSDHCP();
                            }
                            else
                            {
                                adapter.SetDNS(profile.DNS1, profile.DNS2);
                            }
                            progress += step;
                            this.worker.ReportProgress(progress, string.Format("DNS {0}", Properties.Resources.Configured));
                        }
                        else
                        {
                            adapter.Disable();
                            adapter.SetDHCP();
                            progress += 3 * step;
                            this.worker.ReportProgress(progress, string.Format("{0} \"{1}\" {2}", Properties.Resources.Adapter, profile.NetworkAdapter, Properties.Resources.Disabled));
                        }
                    }
                    catch (IndexOutOfRangeException)
                    {
                        
                    }
                }
            }
            catch (Exception exc)
            {
                Global.NotifyCrash(Properties.Resources.Error_ProfileActivating, exc);
            }
        }

        private void ChooseBookmark(object sender, EventArgs e)
        {
            ThumbButtonInfo button = (ThumbButtonInfo)sender;
            scNetworkProfile np = new scNetworkProfile();
            scXmlSerializer.Load(ref np, "np", System.IO.Path.Combine(Global.ProfilesPath, button.Description));
            this.selected = np;
            cmdActivate_Click(sender, null);
        }
        #endregion

        #region Fixer

        private void cmdFix_Click(object sender, RoutedEventArgs e)
        {
            LockGUI(true);
            this.lblProgress.Visibility = this.prgProgress.Visibility = Visibility.Visible;
            this.TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Normal;

            BackgroundWorker fixer = new BackgroundWorker();
            fixer.WorkerReportsProgress = true;
            fixer.WorkerSupportsCancellation = true;
            fixer.DoWork += new DoWorkEventHandler(fixer_DoWork);
            fixer.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            fixer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(fixer_RunWorkerCompleted);

            LockGUI(true);
            fixer.RunWorkerAsync();
        }

        void fixer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            LockGUI(false);
            this.lblProgress.Visibility = this.prgProgress.Visibility = Visibility.Hidden;
            this.TaskbarItemInfo.ProgressState = TaskbarItemProgressState.None;
        }

        void fixer_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker fixer = sender as BackgroundWorker;
            scAdapterProfile[] profiles = this.active.GetProfiles();
            profiles = profiles.Where((p) => p.Enabled).ToArray();

            for (int i = 0; i < profiles.Length; i++)
            {
                scNetworkAdapter adapter = new scNetworkAdapter(profiles[i].NetworkAdapter);
                fixer.ReportProgress(i * 100 / profiles.Length, string.Format("{0} \"{1}\"", Properties.Resources.Repair, adapter.ConnectionName));
                adapter.Repair();
            }
        }
        #endregion
    }
}
